<!DOCTYPE html>
<html lang="en">

<!-- Head tag (contains Google-Analytics、Baidu-Tongji)-->
<head>
  <!-- Google Analytics -->
  

  <!-- Baidu Tongji -->
  
    <script type="text/javascript">
      // Originial
      var _hmt = _hmt || [];
      (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?cdf616a127124dd7ff798963125b304d";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
      })();
    </script>
  

  <!-- Baidu Push -->
  
    <script>
      (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
          bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
          bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
      })();
    </script>
  

  <meta charset="utf-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>

  <meta name="google-site-verification" content="lxDfCplOZbIzjhG34NuQBgu2gdyRlAtMB4utP5AgEBc"/>
  <meta name="baidu-site-verification" content="PpzM9WxOJU"/>

  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <meta name="description" content="It&#39;s an IT blog..."/>
  <meta name="keyword" content="zhuang,IT  blog,Blog"/>
  <link rel="shortcut icon" href="/img/avatar/java-head.png"/>

  <!-- Place this tag in your head or just before your close body tag. -->
  <script async="async" defer="defer" src="https://buttons.github.io/buttons.js"></script>

  
    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css"/>

    <!-- Custom CSS -->
    <link rel="stylesheet" href="/css/beantech.min.css"/>

    <!-- Pygments Highlight CSS -->
    <link rel="stylesheet" href="/css/highlight.css"/>
    <link rel="stylesheet" href="/css/widget.css"/>
    <link rel="stylesheet" href="/css/rocket.css"/>
    <link rel="stylesheet" href="/css/signature.css"/>
    <link rel="stylesheet" href="/css/catalog.css"/>
    <link rel="stylesheet" href="/css/livemylife.css"/>

    
      <!-- wave start -->
      <link rel="stylesheet" href="/css/wave.css"/>
      <!-- wave end -->
    

    
      <!-- top start (article top hot config) -->
      <link rel="stylesheet" href="/css/top.css"/>
      <!-- top end -->
    

    
      <!-- ThemeColor start -->
      <link rel="stylesheet" href="/css/scroll.css"/>
      <!-- ThemeColor end -->
    

    
      <!-- viewer start (Picture preview) -->
      <link rel="stylesheet" href="/css/viewer.min.css"/>
      <!-- viewer end -->
    

    
      <!-- Search start -->
      <link rel="stylesheet" href="/css/search.css"/>
      <!-- Search end -->
    

    
      <!-- ThemeColor start -->
      <link rel="stylesheet" href="/css/themecolor.css"/>
      <!-- ThemeColor end -->
    

    

    
  

  <!-- Custom Fonts -->
  <!-- <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
  <!-- Hux change font-awesome CDN to qiniu -->
  <link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/4.5.0/css/font-awesome.min.css" type="text/css">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <!-- Hux Delete, sad but pending in China <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link
  href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/ css'> -->

  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]-->

  <!-- ga & ba script hoook -->
  <link rel="canonical" href="http://yoursite-url/cn/python/面向对象程序设计/">
  <title>
    
      python基础 &gt; 面向对象程序设计 - either thin | or die
    
  </title>
<meta name="generator" content="Hexo 5.4.0"></head>


<!-- hack iOS CSS :active style -->

	<body ontouchstart="" class="body--light body--dark">


		<!-- ThemeColor -->
		
		<!-- ThemeColor -->
<style type="text/css">
  .body--light {
    --light-mode: none;
    --dark-mode: block;
  }
  .body--dark {
    --light-mode: block;
    --dark-mode: none;
  }
  i.mdui-icon.material-icons.light-mode {
    display: var(--light-mode);
  }
  i.mdui-icon.material-icons.dark-mode {
    display: var(--dark-mode);
  }
</style>
<div class="toggle" onclick="document.body.classList.toggle('body--dark')">
  <i class="mdui-icon material-icons light-mode"></i>
  <i class="mdui-icon material-icons dark-mode"></i>
</div>
<script>
  //getCookieValue
  function getCookieValue(a) {
    var b = document.cookie.match('(^|[^;]+)\\s*' + a + '\\s*=\\s*([^;]+)');
    return b
      ? b.pop()
      : '';
  }
  let themeMode = 'dark';
  if (getCookieValue('sb-color-mode') && (getCookieValue('sb-color-mode') !== themeMode)) {
    let dbody = document.body.classList;
    themeMode === 'dark' ? dbody.remove('body--dark') : dbody.add('body--dark');
  }

  //setCookieValue
  var toggleBtn = document.querySelector(".toggle");
  toggleBtn.addEventListener("click", function () {
    var e = document.body.classList.contains("body--dark");
    var cookieString = e
      ? "dark"
      : "light";
    var exp = new Date();
    exp.setTime(exp.getTime() + 3 * 24 * 60 * 60 * 1000); //3天过期
    document.cookie = "sb-color-mode=" + cookieString + ";expires=" + exp.toGMTString() + ";path=/";
  });
</script>

		

		<!-- Gitter -->
		

		<!-- Navigation (contains search)-->
		<!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header page-scroll">
      <button type="button" class="navbar-toggle">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="/">平平淡淡</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <!-- Known Issue, found by Hux: <nav>'s height woule be hold on by its content. so, when navbar scale out, the <nav> will cover tags. also mask any touch event of tags, unfortunately. -->
    <div id="huxblog_navbar">
      <div class="navbar-collapse">
        <ul class="nav navbar-nav navbar-right">
          <li>
            <a href="/">首页</a>
          </li>

          
          
          
          
          <li>
            <a href="/archive/">
              
              归档
              
              
            </a>
          </li>
          
          
          
          <li>
            <a href="/tags/">
              
              标签
              
              
            </a>
          </li>
          
          
          
          <li>
            <a href="/categories/">
              
              分类
              
              
            </a>
          </li>
          
          
          
          <li>
            <a href="/about/">
              
              关于
              
              
            </a>
          </li>
          
          

          
          <li>
            <a class="popup-trigger">
              <span class="search-icon"></span>搜索</a>
          </li>
          

          <!-- LangSelect -->
          
        </ul>
      </div>
    </div>
    <!-- /.navbar-collapse -->
  </div>
  <!-- /.container -->
</nav>
<!-- progress -->
<div id="progress">
  <div class="line" style="width: 0%;"></div>
</div>

<script>
  // Drop Bootstarp low-performance Navbar Use customize navbar with high-quality material design animation in high-perf jank-free CSS3 implementation
  var $body = document.body;
  var $toggle = document.querySelector('.navbar-toggle');
  var $navbar = document.querySelector('#huxblog_navbar');
  var $collapse = document.querySelector('.navbar-collapse');

  $toggle.addEventListener('click', handleMagic)

  function handleMagic(e) {
    if ($navbar.className.indexOf('in') > 0) {
      // CLOSE
      $navbar.className = " ";
      // wait until animation end.
      setTimeout(function() {
        // prevent frequently toggle
        if ($navbar.className.indexOf('in') < 0) {
          $collapse.style.height = "0px"
        }
      }, 400)
    } else {
      // OPEN
      $collapse.style.height = "auto"
      $navbar.className += " in";
    }
  }
</script>


		<!-- Post Header (contains intro-header、signature、wordcount、busuanzi、waveoverlay) -->
		<!-- Modified by Yu-Hsuan Yen -->
<!-- Post Header -->

  <style type="text/css">
    .body--light {
      /* intro-header */
      --intro-header-background-image-url-home: url('/img/header_img/home_bg1.jpg');
      --intro-header-background-image-url-post: url('/img/header_img/lml_bg.jpg');
      --intro-header-background-image-url-page: url('//img/header_img/lml_bg.jpg');
    }
    .body--dark {
      --intro-header-background-image-url-home: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), url('/img/header_img/home_bg1.jpg');
      --intro-header-background-image-url-post: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), url('/img/header_img/lml_bg.jpg');
      --intro-header-background-image-url-page: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), url('//img/header_img/lml_bg.jpg');
    }

    header.intro-header {
       /*post*/
        background-image: var(--intro-header-background-image-url-post);
        /* background-image: url('/img/header_img/lml_bg.jpg'); */
      
    }

    
      #signature {/*signature*/
        background-image: url('/img/signature/signature.png');
      }
    
  </style>





<header class="intro-header">
  <!-- Signature -->
  <div id="signature">
    <div class="container">
      <div class="row">
        <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
          
          <div class="post-heading">
            <div class="tags">
              
              <a class="tag" href="/tags/#python" title="python">python</a>
              
              <a class="tag" href="/tags/#基础" title="基础">基础</a>
              
            </div>
            <h1>python基础 &gt; 面向对象程序设计</h1>
            <h2 class="subheading"></h2>
            <span class="meta">
              Posted by zhuang on
              2020-11-17
            </span>


            
            <!-- WordCount start -->
            <div class="blank_box"></div>
            <span class="meta">
              Estimated Reading Time <span class="post-count">11</span> Minutes
            </span>
            <div class="blank_box"></div>
            <span class="meta">
              Words <span class="post-count">2.6k</span> In Total
            </span>
            <div class="blank_box"></div>
            <!-- WordCount end -->
            
            
            <!-- 不蒜子统计 start -->
            <span class="meta" id="busuanzi_container_page_pv">
              Viewed <span id="busuanzi_value_page_pv"><i class="fa fa-spinner fa-spin"></i></span> Times
            </span>
            <!-- 不蒜子统计 end -->
            


          </div>
          
        </div>
      </div>
    </div>
  </div>

  
  <!-- waveoverlay start -->
  <div class="preview-overlay">
    <svg class="preview-waves" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto">
      <defs>
        <path id="gentle-wave" d="M-160 44c30 0 58-18 88-18s 58 18 88 18 58-18 88-18 58 18 88 18 v44h-352z"></path>
      </defs>
      <g class="preview-parallax">
        <use xlink:href="#gentle-wave" x="48" y="0" fill=var(--gentle-wave1)></use>
        <use xlink:href="#gentle-wave" x="48" y="3" fill=var(--gentle-wave2)></use>
        <use xlink:href="#gentle-wave" x="48" y="5" fill=var(--gentle-wave3)></use>
        <use xlink:href="#gentle-wave" x="48" y="7" fill=var(--gentle-wave)></use>
      </g>
    </svg>
  </div>
  <!-- waveoverlay end -->
  

</header>



		<!-- Main Content (Post contains
	Pager、
	tip、
	socialshare、
	gitalk、gitment、disqus-comment、
	Catalog、
	Sidebar、
	Featured-Tags、
	Friends Blog、
	anchorjs、
	) -->
		<!-- Modify by Yu-Hsuan Yen -->
<!-- Post Content -->
<article>
  <div class="container">
    <div class="row">
      <!-- Post Container -->
      <div class="col-lg-8 col-lg-offset-1 col-md-10 col-md-offset-1 post-container">

        <h2 id="1-为对象定义类"><a href="#1-为对象定义类" class="headerlink" title="1. 为对象定义类"></a>1. 为对象定义类</h2><h3 id="1-1-定义类"><a href="#1-1-定义类" class="headerlink" title="1.1 定义类"></a>1.1 定义类</h3><p>Python使用<code>class</code>关键字定义类,除了使用变量存储数据域和定义方法，一个类提供了一个特殊的方式：<code>__init__</code>,这个方法被称为初始化程序，它是在创建和初始化这个新对象时被调用的。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> math</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Circle</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self,radius = <span class="number">1</span></span>):</span></span><br><span class="line">        self.radius = radius</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getPerimeter</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> <span class="number">2</span> * self.radius * math.pi</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getArea</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> self.radius * self.radius * math.pi</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">setRadius</span>(<span class="params">self,radius</span>):</span></span><br><span class="line">        self.radius = radius</span><br></pre></td></tr></table></figure>
<p>在定义类的时候，也使用三引号为类进行必要的注释</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Circle</span>:</span></span><br><span class="line">    <span class="string">&#x27;&#x27;&#x27;The Class is Circle&#x27;&#x27;&#x27;</span></span><br><span class="line">    <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p><code>pass</code>：表示空语句。</p>
<p><code>__doc__</code>方法:查看类的帮助文档</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">print</span>(Circle.__doc__)   <span class="comment">#The Class is Circle</span></span><br></pre></td></tr></table></figure>
<h3 id="1-2-构造对象"><a href="#1-2-构造对象" class="headerlink" title="1.2 构造对象"></a>1.2 构造对象</h3><p>构造方法完成两个任务：</p>
<ul>
<li>在内存中为类创建一个对象</li>
<li>调用类的<code>__init__</code>方法来初始化对象。</li>
</ul>
<p>包括初始化程序的所有方法，都有第一个参数<code>self</code>，指向调用方法的对象。<code>__init__</code>方式中的self参数被自动设置为引用刚被创建的对象。</p>
<p><img src="image-20201119223513790.png" alt="image-20201119223513790"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">circlr = Circle(<span class="number">5</span>)   <span class="comment">#实例化circlr对象</span></span><br></pre></td></tr></table></figure>
<p>使用内置函数<code>isinstance()</code>测试一个对象是否为某个类的实例，或使用<code>type()</code>查看对象类型</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">print</span>(<span class="built_in">isinstance</span>(circlr,Circle))   <span class="comment">#True</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">type</span>(circlr)) <span class="comment">#&lt;class &#x27;__main__.Circle&#x27;&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="1-3-访问对象成员"><a href="#1-3-访问对象成员" class="headerlink" title="1. 3 访问对象成员"></a>1. 3 访问对象成员</h3><p>对象成员是指它的数据域和方法，数据域称为实例变量，方法也称为实例方法。</p>
<p>使用圆点运算符(.)访问对象的数据域并调用方法，也称为对象成员访问运算符</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">print</span>(circlr.radius) <span class="comment">#访问circlr对象的radius数据域   5</span></span><br><span class="line"><span class="built_in">print</span>(circlr.getPerimeter())  <span class="comment">#访问circlr对象的getPerimeter方法31.41592653589793</span></span><br></pre></td></tr></table></figure>
<h3 id="1-4self参数"><a href="#1-4self参数" class="headerlink" title="1.4self参数"></a>1.4self参数</h3><p>self是指向对象本身的参数，使用self访问在类定义中的对象成员。一旦一个实例变量被创建，那么它的作用域就是整个类。</p>
<p><img src="image-20201119225424684.png" alt="image-20201119225424684"> </p>
<h3 id="1-5-不变对象和可变对象"><a href="#1-5-不变对象和可变对象" class="headerlink" title="1.5 不变对象和可变对象"></a>1.5 不变对象和可变对象</h3><p><strong><em>当将一个可变对象传给函数时，函数可能会改变这个对象的内容</em></strong></p>
<p>当你将一个对象传递给函数，就是将这个对象的引用传递给函数，但是，传递不可变对象和可变对象之间还有区别：</p>
<ul>
<li>像数字和字符串这样不可变对象参数，函数外的对象的原始值并没有被改变</li>
<li>像Circle的可变对象参数，如果对象的内容在函数内被改变，则对象的原始值被改变</li>
</ul>
<h2 id="2-数据成员与成员方法"><a href="#2-数据成员与成员方法" class="headerlink" title="2.  数据成员与成员方法"></a>2.  数据成员与成员方法</h2><h3 id="2-1-私有成员与公有成员"><a href="#2-1-私有成员与公有成员" class="headerlink" title="2.1 私有成员与公有成员"></a>2.1 私有成员与公有成员</h3><p>为避免直接修改数据域，不让客户端直接访问数据域，称为数据隐藏，并可以通过定义私有数据域实现，私有数据域是以两个下划线开始来定义的，也可以用两个下划线开始来定义私有方法</p>
<p>为了访问数据域，修改数据域，提供get、set方法</p>
<ul>
<li>get方法是指获取器(访问器)</li>
<li>set方法是设置器(修改器)</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Circle</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self,radius = <span class="number">1</span></span>):</span></span><br><span class="line">        <span class="comment">#定义私有成员</span></span><br><span class="line">        self.__radius = radius</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getRadius</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="comment">#在类内部可以直接访问私有成员</span></span><br><span class="line">        <span class="keyword">return</span> self.__radius  </span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">setRadius</span>(<span class="params">self,radius</span>):</span></span><br><span class="line">        self.__radius = radius</span><br><span class="line"></span><br><span class="line">circlr = Circle(<span class="number">5</span>)   <span class="comment">#实例化circlr对象</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#在类外部无法访问类的私有数据成员</span></span><br><span class="line"><span class="comment">#print(circlr.__radius)  #AttributeError: &#x27;Circle&#x27; object has no attribute &#x27;__radius&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(circlr.getRadius())  <span class="comment">#5</span></span><br></pre></td></tr></table></figure>
<p>在类的定义中用下划线作为成员名前缀和后缀表示类的特殊成员：</p>
<ul>
<li><code>_xxx</code>：以一个下划线开头，保护成员。</li>
<li><code>__xxx__</code>：前后各两个下划线，系统定义的特殊成员。</li>
<li><code>__xxx</code>：以两个或更多下划线开头但不以两个或更多下划线结束，表示私有成员。</li>
</ul>
<p><strong><em>在类的外部可以访问到对象的私有数据成员: 对象名.<em>类名_</em>数据成员</em></strong></p>
<h3 id="2-2-数据成员"><a href="#2-2-数据成员" class="headerlink" title="2.2 数据成员"></a>2.2 数据成员</h3><p>数据成员可以大致分为两类：</p>
<ul>
<li>属于对象的数据成员：只能通过对象名访问</li>
<li>属于类的数据成员：只能通过类名或对象名访问</li>
</ul>
<p>利用类数据成员共享性，可以实时获得该类的对象数量</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Demo</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line">    total = <span class="number">0</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__new__</span>(<span class="params">cls, *args, **kwargs</span>):</span>   <span class="comment">#该方法在__init__()之前调用</span></span><br><span class="line">        <span class="keyword">if</span> cls.total &gt;= <span class="number">3</span>:</span><br><span class="line">            <span class="keyword">raise</span> Exception(<span class="string">&#x27;最多创建3个对象&#x27;</span>)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">object</span>.__new__(cls)</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self</span>):</span></span><br><span class="line">        Demo.total += <span class="number">1</span></span><br><span class="line"></span><br><span class="line">t1 = Demo()</span><br><span class="line">t2 = Demo()</span><br><span class="line">t3 = Demo()</span><br><span class="line">t4 = Demo()  <span class="comment">#Exception: 最多创建3个对象</span></span><br></pre></td></tr></table></figure>
<h3 id="2-3-成员方法、类方法、静态方法、抽象方法"><a href="#2-3-成员方法、类方法、静态方法、抽象方法" class="headerlink" title="2.3 成员方法、类方法、静态方法、抽象方法"></a>2.3 成员方法、类方法、静态方法、抽象方法</h3><p>python类的成员方法大致分为公有方法、私有方法、静态方法、类方法和抽象方法几种类型。</p>
<p>属于对象的实例方法：公有方法、私有方法和抽象方法：</p>
<ul>
<li>私有方法：名字以两个或更多个下划线开始</li>
<li>抽象方法：定义在抽象类中并且要求派生类必须重新实现</li>
</ul>
<p>所有实例方法（包括公有方法、私有方法、抽象方法和某些特殊方法）都必须至少有一个名为<code>self</code>的参数，并且必须是方法的第一个形参，self参数代表当前对象。</p>
<p>静态方法和类方法都可以通过类名和对象名调用，但不能直接访问属于对象的成员只能访问属于类的成员。</p>
<ul>
<li>静态方法和类方法不属于任何实例，不会绑定到任何实例上；</li>
<li>类方法一般以<code>cls</code>作为第一参数表示该类自身；</li>
<li>静态方法可以不接受任何参数</li>
</ul>
<h3 id="2-4-属性"><a href="#2-4-属性" class="headerlink" title="2.4 属性"></a>2.4 属性</h3><p>属性是一种特殊形式的成员方法，结合了公开数据成员和成员方法的优点，既可以像成员方法那样对值进行必要的检查，又可以像数据成员一样灵活的访问。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Test</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self,value</span>):</span></span><br><span class="line">        self.__value = value    <span class="comment">#私有数据成员</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @property          </span><span class="comment">#修饰器，定义属性，提供对私有数据成员的访问</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">value</span>(<span class="params">self</span>):</span>   <span class="comment">#只读属性，无法修改和删除</span></span><br><span class="line">        <span class="keyword">return</span> self.__value</span><br><span class="line"></span><br><span class="line">t = Test(<span class="number">3</span>)</span><br><span class="line"><span class="built_in">print</span>(t.value)   <span class="comment">#3</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#AttributeError: can&#x27;t set attribute</span></span><br><span class="line"><span class="comment">#t.value = 5    #只读属性不允许修改值</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#AttributeError: can&#x27;t delete attribute</span></span><br><span class="line"><span class="comment">#del t.value    #试图删除对象属性，失败</span></span><br></pre></td></tr></table></figure>
<p>把属性设置可读、可修改，而不允许删除：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Test</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self,value</span>):</span></span><br><span class="line">        self.__value = value</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__get</span>(<span class="params">self</span>):</span>         <span class="comment">#读取私有数据成员的值</span></span><br><span class="line">        <span class="keyword">return</span> self.__value</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__set</span>(<span class="params">self,v</span>):</span>      <span class="comment">#修改私有数据成员的值</span></span><br><span class="line">        self.__value = v</span><br><span class="line"></span><br><span class="line">    value = <span class="built_in">property</span>(__get, __<span class="built_in">set</span>) <span class="comment">#可读可写属性，指定相应的读写方法</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">show</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="built_in">print</span>(self.__value)</span><br><span class="line"></span><br><span class="line">t = Test(<span class="number">3</span>)</span><br><span class="line"><span class="built_in">print</span>(t.value)   <span class="comment">#允许读取属性值   3</span></span><br><span class="line"></span><br><span class="line">t.value = <span class="number">5</span></span><br><span class="line"><span class="built_in">print</span>(t.value)   <span class="comment">#允许修改属性值   5</span></span><br><span class="line"></span><br><span class="line">t.show()         <span class="comment">#5</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">del</span> t.value   <span class="comment">#AttributeError: can&#x27;t delete attribute</span></span><br></pre></td></tr></table></figure>
<p>将属性设置为可读、可修改、可删除：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">__del</span>(<span class="params">self</span>):</span></span><br><span class="line">    <span class="keyword">del</span> self.__value</span><br><span class="line"></span><br><span class="line">value = <span class="built_in">property</span>(__get, __<span class="built_in">set</span>,__<span class="keyword">del</span>) <span class="comment">#可读可写可删除属性，指定相应的读写方法</span></span><br></pre></td></tr></table></figure>
<h3 id="2-5-类与对象的动态性、混入机制"><a href="#2-5-类与对象的动态性、混入机制" class="headerlink" title="2. 5 类与对象的动态性、混入机制"></a>2. 5 类与对象的动态性、混入机制</h3><p>在Python中可以动态地为自定义类和对象增加数据成员和成员方法，也是Python动态类型的一种体现。</p>
<p>Python类型的动态性可以动态为自定义类及其对象增加新的属性和行为。称为混入机制。</p>
<p>例如：根据不同的用户设置不同的行为能力</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> types</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self,name</span>):</span></span><br><span class="line">        <span class="keyword">assert</span> <span class="built_in">isinstance</span>(name,<span class="built_in">str</span>),<span class="string">&#x27;name must be string&#x27;</span></span><br><span class="line">        self.name = name</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">sing</span>(<span class="params">self</span>):</span></span><br><span class="line">    <span class="built_in">print</span>(self.name + <span class="string">&#x27;  can sing.&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">walk</span>(<span class="params">self</span>):</span></span><br><span class="line">    <span class="built_in">print</span>(self.name + <span class="string">&#x27;  can walk.&#x27;</span>)</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">eat</span>(<span class="params">self</span>):</span></span><br><span class="line">    <span class="built_in">print</span>(self.name + <span class="string">&#x27;  can eat.&#x27;</span>)</span><br><span class="line"></span><br><span class="line">pang = Person(<span class="string">&#x27;pang&#x27;</span>)</span><br><span class="line"><span class="comment">#pang.sing()   #用户不具备该行为</span></span><br><span class="line"></span><br><span class="line">pang.sing = types.MethodType(sing,pang)</span><br><span class="line">pang.sing()    <span class="comment">#pang  can sing.</span></span><br><span class="line"></span><br><span class="line">zhang = Person(<span class="string">&#x27;zhang&#x27;</span>)</span><br><span class="line"><span class="comment">#zhang.sing()    #zhang 不具备sing行为</span></span><br><span class="line">zhang.walk = types.MethodType(walk,zhang)</span><br><span class="line">zhang.walk()   <span class="comment">#zhang  can walk.</span></span><br><span class="line"></span><br><span class="line">zhang.eat = types.MethodType(eat,zhang)</span><br><span class="line">zhang.eat()   <span class="comment">#zhang  can eat.</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">del</span> zhang.walk   <span class="comment">#删除该用户的行为</span></span><br><span class="line">zhang.walk   <span class="comment">#AttributeError: &#x27;Person&#x27; object has no attribute &#x27;walk&#x27;</span></span><br></pre></td></tr></table></figure>
<h2 id="3-继承、多态"><a href="#3-继承、多态" class="headerlink" title="3. 继承、多态"></a>3. 继承、多态</h2><h3 id="3-1-继承"><a href="#3-1-继承" class="headerlink" title="3.1 继承"></a>3.1 继承</h3><p>在派生类中调用基类的方法， 可以使用内置函数<code>super()</code>或者通过<code>基类名.方法名()</code>的方法实现其目的。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> math</span><br><span class="line"><span class="comment">#基类必须继承于object，否则在派生类中将无法使用super()函数</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">GeometricObject</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, color = <span class="string">&#x27;green&#x27;</span>, filled = <span class="literal">True</span></span>):</span></span><br><span class="line">        self.__color = color</span><br><span class="line">        self.__filled = filled</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getColor</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> self.__color</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">setColor</span>(<span class="params">self,color</span>):</span></span><br><span class="line">        self.__color = color</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">isFilled</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> self.__filled</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">setFilled</span>(<span class="params">self,filled</span>):</span></span><br><span class="line">        self.__filled = filled</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__str__</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;color:&#x27;</span> + self.__color + \</span><br><span class="line">                <span class="string">&#x27;and filled:&#x27;</span> + <span class="built_in">str</span>(self.__filled)</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Circle</span>(<span class="params">GeometricObject</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self,radius</span>):</span></span><br><span class="line">        <span class="built_in">super</span>().__init__()</span><br><span class="line">        self.__radius = radius</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getRadius</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> self.__radius</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">setRadius</span>(<span class="params">self,radius</span>):</span></span><br><span class="line">        self.__radius = radius</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getArea</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">pow</span>(self.__radius,<span class="number">2</span>) * math.pi</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getDiameter</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> <span class="number">2</span> * self.__radius</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getPerimeter</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> <span class="number">2</span> * self.__radius * math.pi</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">printCircle</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="built_in">print</span>(self.__str__() + <span class="string">&#x27;radius: &#x27;</span> + <span class="built_in">str</span>(self.__radius))</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span>():</span></span><br><span class="line">    circle = Circle(<span class="number">1.5</span>)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;A circle&#x27;</span>,circle)    <span class="comment">#A circle color:greenand filled:True</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;The radius is &#x27;</span>,circle.getRadius())   <span class="comment">#The radius is  1.5</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;The area is &#x27;</span>, circle.getArea())      <span class="comment">#The area is  7.0685834705770345</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;The diameter is &#x27;</span>, circle.getDiameter())  <span class="comment">#The diameter is  3.0</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;The perimeter is &#x27;</span>, circle.getPerimeter()) <span class="comment">#The perimeter is  9.42477796076938</span></span><br><span class="line"></span><br><span class="line">main()</span><br></pre></td></tr></table></figure>
<p><img src="image-20201123203307387.png" alt="image-20201123203307387"></p>
<p>表示Cricle类继承与GeometericObject类</p>
<ul>
<li><p>python支持多继承，父类有相同名字，子类使用没有指定父类名，则从左到右搜索</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Sub</span>(<span class="params">Sup1, Sup2,...</span>):</span></span><br><span class="line">    initializer</span><br><span class="line">    methods</span><br></pre></td></tr></table></figure>
</li>
<li><p>基类必须继承于object，否则在派生类中将无法使用super()函数</p>
</li>
<li><p>调用基类的构造方法的几种方式</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">super</span>().__init__()</span><br><span class="line"><span class="built_in">super</span>(Circle,self).__init__()</span><br><span class="line">GeometricObject.__init__(self)</span><br></pre></td></tr></table></figure>
</li>
<li><p>私有方法不能被覆盖</p>
</li>
</ul>
<h3 id="3-2-多态"><a href="#3-2-多态" class="headerlink" title="3.2 多态"></a>3.2 多态</h3><p>多态是指子类的对象可以传递给需要父类类型的参数，指基类的同一个方法在不同派生类对象中具有不同的表现和行为。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">GeometricObject</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, color = <span class="string">&#x27;green&#x27;</span>, filled = <span class="literal">True</span></span>):</span></span><br><span class="line">        self.__color = color</span><br><span class="line">        self.__filled = filled</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__str__</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;color:&#x27;</span> + self.__color + \</span><br><span class="line">                <span class="string">&#x27;and filled:&#x27;</span> + <span class="built_in">str</span>(self.__filled)</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Circle</span>(<span class="params">GeometricObject</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self,radius</span>):</span></span><br><span class="line">        <span class="built_in">super</span>().__init__()</span><br><span class="line">        self.__radius =radius</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__str__</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">super</span>().__str__() + \</span><br><span class="line">                <span class="string">&#x27;and radius:&#x27;</span> + <span class="built_in">str</span>(self.__radius)</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Rectangle</span>(<span class="params">GeometricObject</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self,width,height</span>):</span></span><br><span class="line">        <span class="built_in">super</span>(Rectangle,self).__init__()</span><br><span class="line">        self.__width= width</span><br><span class="line">        self.__height = height</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__str__</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">super</span>().__str__() +  \</span><br><span class="line">               <span class="string">&#x27;and width:&#x27;</span> + <span class="built_in">str</span>(self.__width) + \</span><br><span class="line">                <span class="string">&#x27;and height:&#x27;</span> + <span class="built_in">str</span>(self.__height)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span>():</span></span><br><span class="line">    circle = Circle(<span class="number">1.5</span>)</span><br><span class="line">    rectangle = Rectangle(<span class="number">4</span>,<span class="number">5</span>)</span><br><span class="line">    displayObject(circle)     <span class="comment">#color:greenand filled:Trueand radius:1.5</span></span><br><span class="line">    displayObject(rectangle)  <span class="comment">#color:greenand filled:Trueand width:4and height:5</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">displayObject</span>(<span class="params">g</span>):</span></span><br><span class="line">    <span class="built_in">print</span>(g.__str__())</span><br><span class="line">main()</span><br></pre></td></tr></table></figure>
<h2 id="4-特殊方法与运算符重载"><a href="#4-特殊方法与运算符重载" class="headerlink" title="4. 特殊方法与运算符重载"></a>4. 特殊方法与运算符重载</h2><p>Python类有大量的特殊方法：</p>
<ul>
<li>构造方法<code>__init__()</code></li>
<li>析构方法<code>__del__()</code></li>
<li>重载加法运算符方法<code>__add__()</code></li>
<li>……</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Complex</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self,real, imag</span>):</span></span><br><span class="line">        self.__real = real</span><br><span class="line">        self.__imag = imag</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__add__</span>(<span class="params">self, other</span>):</span></span><br><span class="line">        <span class="keyword">return</span> Complex(self.__real + other.__real,self.__imag + other.__imag)</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__str__</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">str</span>(self.__real)  + (<span class="string">&#x27;+&#x27;</span> <span class="keyword">if</span> self.__imag &gt; <span class="number">0</span> <span class="keyword">else</span> <span class="string">&#x27;&#x27;</span>) +<span class="built_in">str</span>(self.__imag) + <span class="string">&#x27;i&#x27;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">c1 = Complex(<span class="number">1</span>,<span class="number">2</span>)</span><br><span class="line">c2 = Complex(<span class="number">3</span>,<span class="number">4</span>)</span><br><span class="line">c3 = c1 + c2</span><br><span class="line"><span class="built_in">print</span>(c3)</span><br></pre></td></tr></table></figure>

        <hr>
        <!-- Pager -->
        <ul class="pager">
          
          <li class="previous">
            <a href="/cn/python/文本处理/" data-toggle="tooltip" data-placement="top" title="python基础 > 文本处理">&larr; Previous Post</a>
          </li>
          
          
          <li class="next">
            <a href="/cn/python/函数/" data-toggle="tooltip" data-placement="top" title="python基础 > 函数">Next Post &rarr;</a>
          </li>
          
        </ul>

        
        <!-- tip start -->
        <!-- tip -->
<!-- tip start -->
<div class="tip">
  <p>
    
      如果您喜欢此博客或发现它对您有用，则欢迎对此发表评论。 也欢迎您共享此博客，以便更多人可以参与。 如果博客中使用的图像侵犯了您的版权，请与作者联系以将其删除。 谢谢 ！
    
  </p>
</div>
<!-- tip end -->

        <!-- tip end -->
        

        
        <hr>

        <!-- comments start -->
        <!-- 1. gitalk comment -->


<!-- 2. gitment comment -->


<!-- 3. disqus comment -->


        <!-- comments end -->
        <hr>

      </div>

      <!-- Catalog: Tabe of Content -->
      <!-- Table of Contents -->

    
      <aside id="sidebar">
        <div id="toc" class="toc-article">
        <strong class="toc-title">目录</strong>
        
          <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#1-%E4%B8%BA%E5%AF%B9%E8%B1%A1%E5%AE%9A%E4%B9%89%E7%B1%BB"><span class="toc-nav-number">1.</span> <span class="toc-nav-text">1. 为对象定义类</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#1-1-%E5%AE%9A%E4%B9%89%E7%B1%BB"><span class="toc-nav-number">1.1.</span> <span class="toc-nav-text">1.1 定义类</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#1-2-%E6%9E%84%E9%80%A0%E5%AF%B9%E8%B1%A1"><span class="toc-nav-number">1.2.</span> <span class="toc-nav-text">1.2 构造对象</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#1-3-%E8%AE%BF%E9%97%AE%E5%AF%B9%E8%B1%A1%E6%88%90%E5%91%98"><span class="toc-nav-number">1.3.</span> <span class="toc-nav-text">1. 3 访问对象成员</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#1-4self%E5%8F%82%E6%95%B0"><span class="toc-nav-number">1.4.</span> <span class="toc-nav-text">1.4self参数</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#1-5-%E4%B8%8D%E5%8F%98%E5%AF%B9%E8%B1%A1%E5%92%8C%E5%8F%AF%E5%8F%98%E5%AF%B9%E8%B1%A1"><span class="toc-nav-number">1.5.</span> <span class="toc-nav-text">1.5 不变对象和可变对象</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#2-%E6%95%B0%E6%8D%AE%E6%88%90%E5%91%98%E4%B8%8E%E6%88%90%E5%91%98%E6%96%B9%E6%B3%95"><span class="toc-nav-number">2.</span> <span class="toc-nav-text">2.  数据成员与成员方法</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-1-%E7%A7%81%E6%9C%89%E6%88%90%E5%91%98%E4%B8%8E%E5%85%AC%E6%9C%89%E6%88%90%E5%91%98"><span class="toc-nav-number">2.1.</span> <span class="toc-nav-text">2.1 私有成员与公有成员</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-2-%E6%95%B0%E6%8D%AE%E6%88%90%E5%91%98"><span class="toc-nav-number">2.2.</span> <span class="toc-nav-text">2.2 数据成员</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-3-%E6%88%90%E5%91%98%E6%96%B9%E6%B3%95%E3%80%81%E7%B1%BB%E6%96%B9%E6%B3%95%E3%80%81%E9%9D%99%E6%80%81%E6%96%B9%E6%B3%95%E3%80%81%E6%8A%BD%E8%B1%A1%E6%96%B9%E6%B3%95"><span class="toc-nav-number">2.3.</span> <span class="toc-nav-text">2.3 成员方法、类方法、静态方法、抽象方法</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-4-%E5%B1%9E%E6%80%A7"><span class="toc-nav-number">2.4.</span> <span class="toc-nav-text">2.4 属性</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-5-%E7%B1%BB%E4%B8%8E%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%8A%A8%E6%80%81%E6%80%A7%E3%80%81%E6%B7%B7%E5%85%A5%E6%9C%BA%E5%88%B6"><span class="toc-nav-number">2.5.</span> <span class="toc-nav-text">2. 5 类与对象的动态性、混入机制</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#3-%E7%BB%A7%E6%89%BF%E3%80%81%E5%A4%9A%E6%80%81"><span class="toc-nav-number">3.</span> <span class="toc-nav-text">3. 继承、多态</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-1-%E7%BB%A7%E6%89%BF"><span class="toc-nav-number">3.1.</span> <span class="toc-nav-text">3.1 继承</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-2-%E5%A4%9A%E6%80%81"><span class="toc-nav-number">3.2.</span> <span class="toc-nav-text">3.2 多态</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#4-%E7%89%B9%E6%AE%8A%E6%96%B9%E6%B3%95%E4%B8%8E%E8%BF%90%E7%AE%97%E7%AC%A6%E9%87%8D%E8%BD%BD"><span class="toc-nav-number">4.</span> <span class="toc-nav-text">4. 特殊方法与运算符重载</span></a></li></ol>
        
        </div>
      </aside>
    



      <!-- Sidebar Container -->
      <div class="
                col-lg-8 col-lg-offset-1
                col-md-10 col-md-offset-1
                sidebar-container">

        <!-- Featured Tags -->
        
        <section>
          <!-- no hr -->
          <h5>
            <a href="/tags/">特色标签</a>
          </h5>
          <div class="tags">
            
            <a class="tag" href="/tags/#python" title="python">python</a>
            
            <a class="tag" href="/tags/#基础" title="基础">基础</a>
            
          </div>
        </section>
        

        <!-- Friends Blog -->
        
        <hr>
        <h5>链友</h5>
        <ul class="list-inline">

          
        </ul>
        
      </div>
    </div>
  </div>
</article>



<!-- anchorjs start -->
<!-- async load function -->
<!-- anchor-js, Doc:http://bryanbraun.github.io/anchorjs/ -->
<script type="text/javascript">
  // async load function
  function async (u, c) {
    var d = document,
      t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) {
      o.addEventListener('load', function(e) {
        c(null, e);
      }, false);
    }
    s.parentNode.insertBefore(o, s);
  };
</script>
<script type="text/javascript">
  //anchor-js, Doc:http://bryanbraun.github.io/anchorjs/
  async ("https://cdn.bootcss.com/anchor-js/1.1.1/anchor.min.js", function() {
    anchors.options = {
      visible: 'hover',
      placement: 'left',
      // icon: 'ℬ'
      icon: '❡'
    };
    anchors.add().remove('.intro-header h1').remove('.subheading').remove('.sidebar-container h5');
  });
</script>
<style>
  /* place left on bigger screen */
  @media all and (min-width: 800px) {
    .anchorjs-link {
      position: absolute;
      left: -0.75em;
      font-size: 1.1em;
      margin-top: -0.1em;
    }
  }
</style>

<!-- anchorjs end -->



		<!-- Footer (contains ThemeColor、viewer) -->
		<!-- Footer -->
<footer>
  <div class="container">
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        <ul class="list-inline text-center">
          

          

          

          

          

          

          

          

        </ul>
        <p class="copyright text-muted">
          Copyright &copy;
          zhuang
          2021
          <br>
          Theme by
          <a target="_blank" rel="noopener" href="http://beantech.org">BeanTech</a>
          <span style="display: inline-block; margin: 0 5px;">
            <i class="fa fa-heart"></i>
          </span>
          re-Ported by
          <a target="_blank" rel="noopener" href="https://v-vincen.life/">Live My Life</a>
        </p>
      </div>
    </div>
  </div>
</footer>

<a id="rocket" href="#top" class=""></a>


  <!-- jQuery -->
  <script type="text/javascript" src="/js/jquery.min.js"></script>
  <!-- Bootstrap Core JavaScript -->
  <script type="text/javascript" src="/js/bootstrap.min.js"></script>
  <!-- Custom Theme JavaScript -->
  <script type="text/javascript" src="/js/hux-blog.min.js"></script>
  <!-- catalog -->
  <script async="true" type="text/javascript" src="/js/catalog.js"></script>
  <!-- totop(rocket) -->
  <script async="true" type="text/javascript" src="/js/totop.js"></script>

  
    <!-- Busuanzi JavaScript -->
    <script async="async" src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
  

  
    <!-- Scroll start -->
    <script async="async" type="text/javascript" src="/js/scroll.js"></script>
    <!-- Scroll end -->
  

  

  

  
    <!-- ribbon -->
    <script type="text/javascript" src="/js/ribbonDynamic.js"></script>
  

  






  <!-- viewer start -->
  <!-- viewer start (Picture preview) -->
  
    <script async="async" type="text/javascript" src="/js/viewer/viewer.min.js"></script>
    <script async="async" type="text/javascript" src="/js/viewer/pic-viewer.js"></script>
  

  <!-- viewer end -->


<script>
  // async load function
  function async (u, c) {
    var d = document,
      t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) {
      o.addEventListener('load', function (e) {
        c(null, e);
      }, false);
    }
    s.parentNode.insertBefore(o, s);
  }

  // fastClick.js
  async ("https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function () {
    var $nav = document.querySelector("nav");
    if ($nav)
      FastClick.attach($nav);
    }
  )
</script>

<!-- Because of the native support for backtick-style fenced code blocks right within the Markdown is landed in Github Pages, From V1.6, There is no need for Highlight.js, so Huxblog drops it officially. -
https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0 - https://help.github.com/articles/creating-and-highlighting-code-blocks/ -->
<!-- <script> async ("http://cdn.bootcss.com/highlight.js/8.6/highlight.min.js", function () { hljs.initHighlightingOnLoad(); }) </script> <link href="http://cdn.bootcss.com/highlight.js/8.6/styles/github.min.css" rel="stylesheet"> -->

<!-- jquery.tagcloud.js -->
<!-- <script> // only load tagcloud.js in tag.html if ($('#tag_cloud').length !== 0) { async ("http://yoursite-url/js/jquery.tagcloud.js", function () { $.fn.tagcloud.defaults = { // size: { start: 1, end: 1, unit: 'em' }, color: {
start: '#bbbbee', end: '#0085a1' } }; $('#tag_cloud a').tagcloud(); }) } </script> -->


		<!-- Search -->
		
		<div class="popup search-popup local-search-popup">
  <span class="popup-btn-close">
    ESC
  </span>
  <div class="container">
    <div class="row">
      <!-- <div class="col-md-9 col-md-offset-1"> -->
      <div class="col-lg-9 col-lg-offset-1 col-md-10 col-md-offset-1 local-search-content">

        <div class="local-search-header clearfix">

          <div class="local-search-input-wrapper">
            <span class="search-icon">
              <i class="fa fa-search fa-lg" style="margin: 25px 10px 25px 20px;"></i>
            </span>
            <input autocomplete="off" placeholder="搜索..." type="text" id="local-search-input">
          </div>
        </div>
        <div id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>


  
    <script src="/js/ziploader.js"></script>
  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.json";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    // monitor main search box;
    var onPopupClose = function (e) {
      $('.popup').fadeOut(300);
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $('.popup').fadeIn(300);
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }
    // get search zip version
    $.get('/searchVersion.json?t=' + (+new Date()), function (res) {
      if (localStorage.getItem('searchVersion') !== res) {
        localStorage.setItem('searchVersion', res);
        initSearchJson();
      }
    });

    function initSearchJson() {
      initLoad(['/search.flv'], {
        loadOptions: {
          success: function (obj) {
            localStorage.setItem('searchJson', obj['search.json'])
          },
          error: function (e) {
            return console.log(e)
          }
        },
        returnOptions: {
          'json': TYPE_TEXT
        },
        mimeOptions: {
          'json': 'application/json'
        }
      })
    }
    // search function;
    var searchFunc = function (search_id, content_id) {
      'use strict';
      isfetched = true;
      var datas = JSON.parse(localStorage.getItem('searchJson'));
      // console.log(search_id)
      var input = document.getElementById(search_id);
      var resultContent = document.getElementById(content_id);
      var inputEventFunction = function () {
        var searchText = input.value.trim().toLowerCase();
        var keywords = searchText.split(/[\s\-]+/);
        if (keywords.length > 1) {
          keywords.push(searchText);
        }
        var resultItems = [];
        if (searchText.length > 0) {
          // perform local searching
          datas.forEach(function (data) {
            var isMatch = false;
            var hitCount = 0;
            var searchTextCount = 0;
            var title = data.title
              ? data.title.trim()
              : '';
            var titleInLowerCase = title.toLowerCase();
            var content = data.content
              ? data.content.trim().replace(/<[^>]+>/g, "")
              : '';
            var contentInLowerCase = content.toLowerCase();
            var articleUrl = decodeURIComponent(data.url);

            var date = data.date;
            var dateTime = date.replace(/T/, " ").replace(/.000Z/, "");
            var imgUrl = data.header_img;
            


            var indexOfTitle = [];
            var indexOfContent = [];
            // only match articles with not empty titles
            keywords.forEach(function (keyword) {
              function getIndexByWord(word, text, caseSensitive) {
                var wordLen = word.length;
                if (wordLen === 0) {
                  return [];
                }
                var startPosition = 0,
                  position = [],
                  index = [];
                if (!caseSensitive) {
                  text = text.toLowerCase();
                  word = word.toLowerCase();
                }
                while ((position = text.indexOf(word, startPosition)) > -1) {
                  index.push({position: position, word: word});
                  startPosition = position + wordLen;
                }
                return index;
              }
              indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
              indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
            });
            if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
              isMatch = true;
              hitCount = indexOfTitle.length + indexOfContent.length;
            }
            // show search results
            if (isMatch) {
              // sort index by position of keyword
              [indexOfTitle, indexOfContent].forEach(function (index) {
                index.sort(function (itemLeft, itemRight) {
                  if (itemRight.position !== itemLeft.position) {
                    return itemRight.position - itemLeft.position;
                  } else {
                    return itemLeft.word.length - itemRight.word.length;
                  }
                });
              });
              // merge hits into slices
              function mergeIntoSlice(text, start, end, index) {
                var item = index[index.length - 1];
                var position = item.position;
                var word = item.word;
                var hits = [];
                var searchTextCountInSlice = 0;
                while (position + word.length <= end && index.length != 0) {
                  if (word === searchText) {
                    searchTextCountInSlice++;
                  }
                  hits.push({position: position, length: word.length});
                  var wordEnd = position + word.length;
                  // move to next position of hit
                  index.pop();
                  while (index.length != 0) {
                    item = index[index.length - 1];
                    position = item.position;
                    word = item.word;
                    if (wordEnd > position) {
                      index.pop();
                    } else {
                      break;
                    }
                  }
                }
                searchTextCount += searchTextCountInSlice;
                return {hits: hits, start: start, end: end, searchTextCount: searchTextCountInSlice};
              }
              var slicesOfTitle = [];
              if (indexOfTitle.length != 0) {
                slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
              }
              var slicesOfContent = [];
              while (indexOfContent.length != 0) {
                var item = indexOfContent[indexOfContent.length - 1];
                var position = item.position;
                var word = item.word;
                // cut out 100 characters
                var start = position - 20;
                var end = position + 80;
                if (start < 0) {
                  start = 0;
                }
                if (end < position + word.length) {
                  end = position + word.length;
                }
                if (end > content.length) {
                  end = content.length;
                }
                slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
              }
              // sort slices in content by search text's count and hits' count
              slicesOfContent.sort(function (sliceLeft, sliceRight) {
                if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                  return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                  return sliceRight.hits.length - sliceLeft.hits.length;
                } else {
                  return sliceLeft.start - sliceRight.start;
                }
              });
              // select top N slices in content
              var upperBound = parseInt('1');
              if (upperBound >= 0) {
                slicesOfContent = slicesOfContent.slice(0, upperBound);
              }
              // highlight title and content
              function highlightKeyword(text, slice) {
                var result = '';
                var prevEnd = slice.start;
                slice.hits.forEach(function (hit) {
                  result += text.substring(prevEnd, hit.position);
                  var end = hit.position + hit.length;
                  result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                  prevEnd = end;
                });
                result += text.substring(prevEnd, slice.end);
                return result;
              }
              var resultItem = '';

              // if (slicesOfTitle.length != 0) {   resultItem += "<li><a target='_blank' href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>"; } else {   resultItem += "<li><a target='_blank' href='" +
              // articleUrl + "' class='search-result-title'>" + title + "</a>"; } slicesOfContent.forEach(function (slice) {   resultItem += "<a target='_blank' href='" + articleUrl + "'><p class=\"search-result\">" + highlightKeyword(content, slice) +
              // "...</p></a>"; }); resultItem += "</li>";

              if (slicesOfTitle.length != 0) {
                resultItem += "<a target='_blank' href='" + articleUrl + "' class='search-result'><div class='search-result-left'><div class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</div><time class='search-result-date'>" + dateTime + "</time>";
              } else {
                resultItem += "<a target='_blank' href='" + articleUrl + "' class='search-result'><div class='search-result-left'><div class='search-result-title'>" + title + "</div><time class='search-result-date'>" + dateTime + "</time>";
              }
              slicesOfContent.forEach(function (slice) {
                resultItem += "<p class=\"search-result-content\">" + highlightKeyword(content, slice) + "...</p>";
              });
              resultItem += "</div><div class='search-result-right'><img class='media-image' src='" + imgUrl + "' width='64px' height='48px'></img></div></a>";

              resultItems.push({item: resultItem, searchTextCount: searchTextCount, hitCount: hitCount, id: resultItems.length});
            }
          })
        };

        if (keywords.length === 1 && keywords[0] === "") {
          resultContent.innerHTML = '<div id="no-result"></div>'
        } else if (resultItems.length === 0) {
          resultContent.innerHTML = '<div id="no-result"></div>'
        } else {
          resultItems.sort(function (resultLeft, resultRight) {
            if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
              return resultRight.searchTextCount - resultLeft.searchTextCount;
            } else if (resultLeft.hitCount !== resultRight.hitCount) {
              return resultRight.hitCount - resultLeft.hitCount;
            } else {
              return resultRight.id - resultLeft.id;
            }
          });
          var searchResultList = '<div class=\"search-result-list\">';
          resultItems.forEach(function (result) {
            searchResultList += result.item;
          })
          searchResultList += "</div>";
          resultContent.innerHTML = searchResultList;
        }
      }
      if ('auto' === 'auto') {
        input.addEventListener('input', inputEventFunction);
      } else {
        $('.search-icon').click(inputEventFunction);
        input.addEventListener('keypress', function (event) {
          if (event.keyCode === 13) {
            inputEventFunction();
          }
        });
      }
      // remove loading animation
      $('body').css('overflow', '');
      proceedsearch();
    }
    // handle and trigger popup window;
    $('.popup-trigger').click(function (e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc('local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });
    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function (e) {
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 && $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });

    document.addEventListener('mouseup', (e) => {
      var _con = document.querySelector(".local-search-content");
      if (_con) {
        if (!_con.contains(e.target)) {
          onPopupClose();
        }
      }
    });
  </script>


		
	<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ["$","$"], ["\\(","\\)"] ],
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
            processEscapes: true
        }
    });
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax();
        for (var i = 0; i < all.length; ++i)
            all[i].SourceElement().parentNode.className += ' has-jax';
    });
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</body>
</html>
